import { useState, useEffect, useRef } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card, Space, Button, Form, Input, Badge, message, Drawer, notification } from 'antd';
import { connect, useIntl } from 'umi';
import {
  ResourceGrpSelect,
  OpMasterSelect,
  ResourceSelect,
  EmpSelect,
} from '@/components/FormItemSelect';
import request from '@/utils/request';
import { EditableProTable } from '@ant-design/pro-table';
import type { ProColumns } from '@ant-design/pro-table';

const apiURL = '/api/services/app/JobOper/';

const ViewPage = (props: any) => {
  const [params, setParams] = useState({ isSub: 0, isOpComp: 0, isReleased: 1 });
  const [freshNum, setFreshNum] = useState(0);
  const [record, setRecord] = useState<any[]>([]);
  const [empName, setEmpName] = useState('');
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [editableKeys, setEditableKeys] = useState<any[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [editSelectRow, setEditSelectRow] = useState<any>({});
  const formRef = useRef<any>();
  const intl = useIntl();

  useEffect(() => {
    fetchData();
  }, [params, freshNum]);

  const setSelRows = (keys: any, rows: any) => {
    setRecord(rows);
    setSelectedRowKeys(keys);
  };

  const onFinish = (values: any) => {
    setFreshNum(freshNum + 1);
    values.isSub = 0;
    values.isOpComp = 0;
    values.isReleased = 1;
    setParams(values);
  };

  const resetForm = () => {
    formRef.current.resetFields();
  };

  const operateLabor = (act: string = 'BeginLabor') => {
    if (record.length <= 0) {
      message.warning(intl.formatMessage({ id: 'pages.selectAtLeastOneRecord' }));
      return;
    }
    if (!empName || empName === '') {
      message.warning(intl.formatMessage({ id: 'pages.selectEmployee' }));
      return;
    }
    const data: any = [];
    const invalidRec = record.filter((x) => x.qty == 0);
    if (invalidRec.length > 0) {
      message.warning(intl.formatMessage({ id: 'pages.qtyLaborIsInvalid' }));
      return;
    }
    record.forEach((element: any) => {
      if (element.qty > 0) {
        data.push({
          id: element.id,
          userId: empName,
          qty: element.qty,
        });
      }
    });
    request(apiURL + act, {
      method: 'POST',
      data,
    }).then((response) => {
      if (response && response.success) {
        const result = response.result;
        if (result.success) {
          notification.info({
            message: intl.formatMessage({ id: 'pages.system' }),
            description: result.message,
          });
          fetchData();
        } else {
          notification.error({
            message: intl.formatMessage({ id: 'pages.error' }),
            description: result.message,
          });
        }
      }
    });
  };

  const switchDraw = () => {
    setVisible(!visible);
  };

  const fetchData = () => {
    setLoading(true);
    request(apiURL + 'GetList', {
      method: 'GET',
      params: {
        ...params,
        skipCount: 0,
        maxResultCount: 0,
      },
    }).then((response) => {
      if (response) {
        if (response.success) {
          response.result.items.forEach((element: any) => {
            element.qty = 0;
          });
          setDataSource(response.result.items);
          setLoading(false);
        }
      }
    });
  };

  const onChange = (values: any[]) => {
    setDataSource(values);
  };

  const checkQty = (rule: any, value: any, callback: any) => {
    if (value) {
      if (editSelectRow.assemble.requiredQty - editSelectRow.completeQty < value || value <= 0) {
        callback(intl.formatMessage({ id: 'pages.qtyExceedsRequirement' }));
      } else {
        callback();
      }
    } else {
      callback(intl.formatMessage({ id: 'pages.enterQty' }));
    }
  };

  const columnsEdit: ProColumns[] = [
    {
      title: intl.formatMessage({ id: 'pages.jobNum' }),
      dataIndex: 'jobNum',
      width: 100,
      editable: false,
    },
    {
      title: intl.formatMessage({ id: 'pages.assemblySeq' }),
      dataIndex: 'assemblySeq',
      width: 65,
      editable: false,
    },
    {
      title: intl.formatMessage({ id: 'pages.partNum' }),
      dataIndex: 'partNum',
      width: 120,
      editable: false,
    },
    {
      title: intl.formatMessage({ id: 'pages.partDescription' }),
      dataIndex: 'partDescription',
      ellipsis: true,
      editable: false,
      width: 220,
    },
    {
      title: intl.formatMessage({ id: 'pages.requiredQty' }),
      width: 100,
      align: 'center',
      editable: false,
      render: (_: any, record: any) => <span>{record.assemble?.requiredQty}</span>,
    },
    {
      title: intl.formatMessage({ id: 'pages.completeQty' }),
      dataIndex: 'completeQty',
      editable: false,
      width: 80,
    },
    {
      title: intl.formatMessage({ id: 'pages.IUM' }),
      width: 80,
      editable: false,
      render: (_: any, record: any) => <span>{record.assemble?.ium}</span>,
    },
    {
      title: intl.formatMessage({ id: 'pages.oprSeq' }),
      dataIndex: 'oprSeq',
      width: 65,
      editable: false,
    },
    {
      title: intl.formatMessage({ id: 'pages.opDesc' }),
      dataIndex: 'opDesc',
      width: 100,
      editable: false,
      render: (text: any, record: any) => (
        <span>
          {text} {record.opComplete ? <Badge status="success" /> : ''}
        </span>
      ),
    },
    {
      title: intl.formatMessage({ id: 'pages.startDate' }),
      dataIndex: 'startDate',
      width: 105,
      editable: false,
      valueType: 'dateTime',
    },
    {
      title: intl.formatMessage({ id: 'pages.estProdHours' }),
      dataIndex: 'estProdHours',
      width: 65,
      editable: false,
      valueType: 'digit',
    },
    {
      title: intl.formatMessage({ id: 'pages.resourceGrpID' }),
      dataIndex: 'resourceGrpID',
      width: 100,
      editable: false,
    },
    {
      title: intl.formatMessage({ id: 'pages.resourceID' }),
      dataIndex: 'resourceID',
      width: 100,
      editable: false,
    },
    {
      title: intl.formatMessage({ id: 'pages.contractLabor' }),
      dataIndex: 'contractID',
      width: 100,
      fixed: 'right',
      editable: false,
    },
    {
      title: intl.formatMessage({ id: 'pages.qty' }),
      dataIndex: 'qty',
      valueType: 'digit',
      width: 120,
      fixed: 'right',
      formItemProps: {
        rules: [
          {
            required: true,
            validator: checkQty,
          },
        ],
      },
    },
    {
      title: intl.formatMessage({ id: 'pages.operation' }),
      valueType: 'option',
      width: 120,
      fixed: 'right',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            setEditSelectRow(record);
            action?.startEditable?.(record.id);
          }}
        >
          {intl.formatMessage({ id: 'pages.edit' })}
        </a>,
      ],
    },
  ];

  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };

  return (
    <PageHeaderWrapper title={false} breadcrumbRender={false} ghost>
      <Card
        title={intl.formatMessage({ id: 'menu.manufacture.mfgLabor' })}
        extra={
          <Form layout="inline">
            <EmpSelect
              tooltip={intl.formatMessage({ id: 'pages.addEmployeeInDepartment(MD)' })}
              showSearch
              width={100}
              name="userId"
              label={intl.formatMessage({ id: 'pages.employee' })}
              onChange={setEmpName}
              params={{
                deptCode: 'MD',
              }}
            />
            <Form.Item>
              <Space key="S1">
                <Button type="primary" onClick={() => operateLabor('DispLabor')}>
                  {intl.formatMessage({ id: 'pages.dispatch' })}
                </Button>
                <Button type="primary" onClick={() => operateLabor()}>
                  {intl.formatMessage({ id: 'pages.startlabor' })}
                </Button>
                <Button type="default" danger onClick={() => operateLabor('CallLabor')}>
                  {intl.formatMessage({ id: 'pages.end' })}
                </Button>
                <Button type="default" onClick={switchDraw}>
                  {intl.formatMessage({ id: 'pages.search' })}
                </Button>
              </Space>
            </Form.Item>
          </Form>
        }
      >
        <EditableProTable
          rowKey="id"
          scroll={{ x: 'max-content', y: 500 }}
          loading={loading}
          columns={columnsEdit}
          recordCreatorProps={false}
          value={dataSource}
          onChange={onChange}
          rowSelection={{
            selectedRowKeys,
            onChange: setSelRows,
          }}
          bordered
          tableAlertRender={false}
          tableAlertOptionRender={false}
          editable={{
            type: 'multiple',
            actionRender: (row, config, dom) => [dom.save, dom.cancel],
            onSave: async (rowKey, data, row) => {
              console.log(rowKey, data, row);
              setSelectedRowKeys([]);
            },
            editableKeys,
            onChange: setEditableKeys,
          }}
        />
      </Card>
      <Drawer
        title={intl.formatMessage({ id: 'pages.advancedSearch' })}
        width={400}
        placement="right"
        closable={false}
        visible={visible}
        onClose={switchDraw}
        mask={true}
        maskClosable={true}
        footer={
          <Button type="primary" onClick={switchDraw}>
            {intl.formatMessage({ id: 'pages.close' })}
          </Button>
        }
      >
        <Form {...layout} ref={formRef} onFinish={onFinish}>
          <Form.Item label={intl.formatMessage({ id: 'pages.jobNum' })} name="jobNum">
            <Input />
          </Form.Item>
          <Form.Item label={intl.formatMessage({ id: 'pages.partNum' })} name="partNum">
            <Input />
          </Form.Item>
          <OpMasterSelect name="opDesc" label={intl.formatMessage({ id: 'pages.opDesc' })} />
          <ResourceGrpSelect
            name="resourceGrpID"
            label={intl.formatMessage({ id: 'pages.resourceGrpID' })}
          />
          <ResourceSelect
            name="resourceID"
            label={intl.formatMessage({ id: 'pages.resourceID' })}
          />
          <EmpSelect
            showSearch
            name="userId"
            label={intl.formatMessage({ id: 'pages.employee' })}
            params={{
              deptCode: 'MD',
            }}
          />
          <Form.Item wrapperCol={{ offset: 5 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                {intl.formatMessage({ id: 'pages.search' })}
              </Button>
              <Button type="default" onClick={resetForm}>
                {intl.formatMessage({ id: 'pages.reset' })}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Drawer>
    </PageHeaderWrapper>
  );
};

export default connect(({ Abp, user }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: user.currentUser,
}))(ViewPage);
